package cool.taomu.toolkit.template

import com.google.inject.Inject
import cool.taomu.toolkit.Context
import cool.taomu.toolkit.antlr4.Antlr4Entry
import cool.taomu.toolkit.antlr4.template.engie.templateidentify.TempIdentifyBaseListener
import cool.taomu.toolkit.antlr4.template.engie.templateidentify.TempIdentifyLexer
import cool.taomu.toolkit.antlr4.template.engie.templateidentify.TempIdentifyParser
import java.io.File
import java.io.StringWriter
import java.util.Map
import java.util.Stack
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.LoggerFactory

class MultiTemplate {
    val static LOG = LoggerFactory.getLogger(MultiTemplate)

    @Inject
    Context context;

    def multiTemplate(String path, Map<String, Object> dataModel) {
        var writer = new StringWriter();
        var type = new Stack<String>();
        try {
            writer.flush();
            var content = FileUtils.readFileToString(new File(path), "UTF-8");
            val entry = new Antlr4Entry()

            val lexerClass = TempIdentifyLexer
            val parserClass = TempIdentifyParser

            val realListener = new TempIdentifyBaseListener()
            val handler = new ListenerInvocationHandler(realListener, context, type, writer, dataModel)

            entry.analyzer(lexerClass, parserClass, realListener.getClass()).entry(realListener.getClass(), "start",
                content, handler)
        } catch (Exception ex) {
            writer.flush();
            LOG.info(ExceptionUtils.getStackTrace(ex));
            writer.append(ExceptionUtils.getStackTrace(ex))
        }
        return writer;

    }
}
